//
//  MOauthViewController.swift
//  iOSweibo
//
//  Created by lzm on 16/5/12.
//  Copyright © 2016年 lzm. All rights reserved.
//

import UIKit
import SVProgressHUD

class MOauthViewController: UIViewController {
    override func loadView() {
//        super.loadView()
        view = webView
        webView.delegate = self
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = GlobalBKGColor
        
        //设置登录navigationItem
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "aotuFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //设置登录title
        navigationItem.title = "登录"
        
        //使用webView加载数据
        let URLString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        webView.loadRequest(NSURLRequest(URL: NSURL(string: URLString)!))
        
        SVProgressHUD .showWithStatus("正在拼命加载中...")
        
        
    }
    @objc private func aotuFill(){
        //document.getElementById("userId").value="164860659@qq.com";
        //document.getElementById("passwd").value="aa15902068473";
        let jsString = "document.getElementById('userId').value='164860659@qq.com';document.getElementById('passwd').value='aa15902068473';"
//        MPrint(items: "")
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    @objc private func close(){
        SVProgressHUD .dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    private lazy var webView:UIWebView = UIWebView()
}
extension MOauthViewController : UIWebViewDelegate
{
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD .dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //请求连接
        let url = request.URL!
        
        //拿到url的前缀,判断是否为授权回调地址,如果不是授权回调地址,就继续让它加载
        if !url.absoluteString.hasPrefix(redirect_uri)
        {
            return true
        }
        else{
            //到了else表示前缀是授权回调地址
            let query = url.query!
//            MPrint(items:" quety:\(url.absoluteString)")
            let codeStr = "code="
            if query.hasPrefix(codeStr)
            {
                let code  = (query as NSString).substringFromIndex(codeStr.characters.count)
                MPrint(items: "code:\(code)")
                //拿到Token连接
                MUserAccountViewModel.sharedInstance.loadAccessToken(code, callback: { (error) -> () in
                    if error != nil
                    {
                        SVProgressHUD.showErrorWithStatus("你的网络不给力...")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    }
                    else
                    {
                        self.close()
                        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                        appDelegate.switchRootVC(MWelcomeVCViewController())
                        
                    }
                    
                })
            }
            else
            {
                 close()
            }
        }
        return false
    }
}
